﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace Ebc.DesignerDsl.CustomCode
{
    public class ConnectionListSelectionEditor : UITypeEditor
    {
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if(!(value is ConnectionSelectionProperty))
            {
                return value;
            }

            var service = ((IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)));
            var lsProperty = value as ConnectionSelectionProperty;
            var dropDown = new ConnectionListSelectionEditorView();

            dropDown.SelectedTypeBox.Items.AddRange(lsProperty.GetSelectedTypes(context).ToArray());
            dropDown.OtherTypeBox.Items.AddRange(lsProperty.GetOtherTypes(context).ToArray());
    
            dropDown.SelectedTypeBox.Click += (sender, e) =>
            {
                var setter = dropDown.SelectedTypeBox.SelectedItem as Tuple<string, Type>;

                if (setter != null)
                {
                    lsProperty.SetSelectedItem(setter, SelectedItemType.UsedSelectedType);
                    service.CloseDropDown();
                }
            };

            dropDown.OtherTypeBox.Click += (sender, e) =>
            {
                var setter = dropDown.OtherTypeBox.SelectedItem as Tuple<string, Type>;

                if (setter != null)
                {
                    lsProperty.SetSelectedItem(setter, SelectedItemType.UsedOtherType);
                    service.CloseDropDown();
                }
            };

            dropDown.NewType += type =>
            {
                if (!string.IsNullOrEmpty(type))
                {
                    lsProperty.SetSelectedItem(new Tuple<string, Type>(type, null), SelectedItemType.CreatedNew);
                    service.CloseDropDown();
                }
            };

            service.DropDownControl(dropDown);

            return lsProperty;
        }

        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.DropDown;
        }
    }
}